package upicgame.game.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import upicgame.entity.Game;
import upicgame.game.service.GameService;
import upicgame.utils.Page;

import javax.annotation.Resource;
import java.util.List;

/*
 *Created by GHW
 *Description:Controller 用户浏览 搜索游戏等。
 *2019/12/24 16:04
 */
@Controller
public class UserToGameController {
    @Resource
    private GameService gs;

    //游戏分页全查
    @RequestMapping("user_gameList")
    public String findAllGameByPage(Model model, Integer pageNum) {
        try {
//       如果当前页为空，那么当前页=1
            if (pageNum == null) {
                pageNum = 1;
            }
//      查找总数据条数
            int count = gs.findCount();
//      每页显示多少条
            int pageSize = 5;
//      分页查出所有游戏，game返回list结果集
            List<Game> game = gs.findAllGameByPage(pageNum, pageSize);
//      将game放入page中
            Page<Game> p = new Page<>(pageNum, pageSize, game);
//      设置总条数
            p.setTotalCount(count);
            model.addAttribute("userGameList", p);
//            System.out.println("From Controller:[user_gameList] ：" + p);
            return "game-review.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("From Controller [user_gameList]: 抛出异常");
        }
        return "查找出错，请检查";
    }


    //模糊搜索
    @RequestMapping("fuzzyFind")
    public String findAllGameByPageWithFuzzy(Model model, Integer pageNum, String gameName) {
        try {
            //当前页为空则为第一页
            if (pageNum == null) {
                pageNum = 1;
            }
            //查找总数据条数
            int count = gs.findCount();
            //每页显示3条数据
            Integer pageSize = 3;
            //将模糊搜索结果返回list结果集
            List<Game> game = gs.findAllGameByPageWithFuzzy(pageNum, pageSize, gameName);
            //将游戏放入page.list中，以实现游戏分页
            Page<Game> page = new Page<>(pageNum, 5, game);
            //设置查询出来的总条数
            page.setTotalCount(count);
            //session
            model.addAttribute("userGameList", page);
            //返回结果渲染至前端页面
            return "game-review.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("From Controller [fuzzyFind] : 模糊搜索出错，请检查");
        }
        return null;
    }

    //点击游戏名称跳到详情页
    @RequestMapping("game_detail")
    public String toSingleGameById(Model model, Integer id) {
        try {
            //查找游戏
            assert id != null;
            Game game = gs.findGameById(id);
            System.out.println("From Controller [game_detail]:" + game);
            model.addAttribute("gameDetail", game);
            return "single-game-review.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("From Controller [game_detail]:查找游戏出错，请检查后重试");
        }
        return null;
    }
}
